package com.ym.controller.doctor.self;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ym.base.enums.FlagEnum;
import com.ym.common.annotations.CustomConstraint;
import com.ym.common.constant.Constants;
import com.ym.common.utils.page.PageDomain;
import com.ym.core.annotation.Log;
import com.ym.core.domain.APIResponse;
import com.ym.core.domain.BaseController;
import com.ym.core.shiro.ShiroUtil;
import com.ym.core.utils.tkmybatis.TK;
import com.ym.medical.domain.entity.*;
import com.ym.medical.domain.param.CounsellingRoomParam;
import com.ym.medical.domain.param.DoctorDetailsParam;
import com.ym.medical.domain.param.DoctorGoodParam;
import com.ym.medical.domain.param.HospitalParam;
import com.ym.medical.domain.param.InformationParam;
import com.ym.medical.domain.param.LabelsParam;
import com.ym.medical.domain.param.UserReplayTemplateParam;
import com.ym.medical.domain.vo.*;
import com.ym.medical.enums.CounsellingRoomCourTypeEnum;
import com.ym.medical.enums.CounsellingRoomStateEnum;
import com.ym.medical.enums.InformationInforStateEnum;
import com.ym.medical.enums.InquiryOrderIoTypeEnum;
import com.ym.medical.enums.InquiryOrderStateEnum;
import com.ym.medical.service.*;
import com.ym.spring.SessionContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "医生端-个人中心")
@RestController
//@ApiSign
@RequestMapping(value = "/doctor/self",headers = Constants.Api.VERSION)
@Validated
public class DoctorSelfController extends BaseController {
	private static final Logger LOGGER = LoggerFactory.getLogger(DoctorSelfController.class);

	@Autowired
	private IResultDoctorSV resultDoctorService;
	@Autowired
	private ICommonSV commonSV;
	@Autowired
	private ICommentRecordSV commentRecordSV;
	@Autowired
	private IDoctorDetailsSV doctorDetailsSV;
	@Autowired
	private IDoctorSelfSV doctorSelfSV;
	@Autowired
	private ICounsellingRoomSV counsellingRoomService;
	@Autowired
	private IDoctorServiceItemSV doctorServiceItemSV;
	@Autowired
	private IAccountSV accountSV;
	@Autowired
	private IConsumeDetailsSV consumeDetailsSV;
	@Autowired
	private ISysDictSV sysDictSV;

	@Autowired
	private IInquiryOrderSV inquiryOrderSV;

	@Autowired
	private IRelevantCertRecordSV relevantCertRecordSV;

	@Autowired
	private IInformationSV informationSV;

	@Autowired
	private IPersonalTransactionOrderSV personalTransactionOrderSV;

	@Autowired
	private IUserReplayTemplateSV userReplayTemplateSV;

	@Autowired
	private IDoctorUpdateInfoSV doctorUpdateInfoSV;

	@Autowired
	private IDoctorUpdateRelationSV doctorUpdateRelationSV;

	@Autowired
	private IHospitalSV hospitalSV;

	@Autowired
	private ILabelsSV labelsSV;

	@Autowired
	private IDoctorLabelSV doctorLabelSV;

	@Log
	@ApiOperation("医生端-医生个人信息")
	@GetMapping(value = "/id")
	public APIResponse<DoctorDetailAllInfoVo> selectByDoctorId() {
		Long doctorId = ShiroUtil.getLoginId();
		List<DoctorDetailAllInfoVo> resultDocDetail = doctorDetailsSV.listDoctorAllInfo(DoctorDetailsParam.builder().id(doctorId).build());
		return successData(resultDocDetail.isEmpty() ? null : resultDocDetail.get(0));
	}

	@Log
	@ApiOperation("医生个人接诊状态修改")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "status", value = "接诊状态:00否01是", required = true, paramType = "query")
	})
	@PostMapping(value = "/accept", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
	public APIResponse accept(
			@NotEmpty @CustomConstraint(FlagEnum.class) String status
	) {
		DoctorDetailsEntity doctorDetails = new DoctorDetailsEntity();
		doctorDetails.setId(ShiroUtil.getLoginId());
		doctorDetailsSV.updateById(doctorDetails);
		return success();
	}

	@Log
	@ApiOperation("医生个人信息修改")
	@PostMapping(value = "/insert", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
	public APIResponse updateByDoctorId(DoctorDetailsEntity doctorDetails, UserEntity user) {
		if (doctorDetails != null) {
			doctorDetails.setId(ShiroUtil.getLoginId());
		}
		if (user != null) {
			user.setId(ShiroUtil.getLoginId());
		}
		doctorDetailsSV.updateByDoctorId(doctorDetails, user);
		return success();
	}

	@Log
	@ApiOperation("医生擅长信息/标签 展示")
	@GetMapping(value = "/good/list")
	public APIResponse<PageInfo<LabelsEntity>> selectDoctorGood(@RequestParam Long doctorId,
																@RequestParam(defaultValue = "1", required = false) int pageNum,
																@RequestParam(defaultValue = "5") int pageSize) {

		PageInfo<LabelsEntity> labels = resultDoctorService.selectDoctorGood(doctorId, pageNum, pageSize);
		return successData(labels);
	}

	@Log(dataBase = false, printBody = false)
	@ApiOperation("医生热度咨询标签")
	@GetMapping(value = "/hot/labels")
	public APIResponse<List<LabelsEntity>> hotLabels(
			@RequestParam Long doctorId
	) {
		List<LabelsEntity> labels = commentRecordSV.hotLabels(doctorId);
		return successData(labels);
	}

	@Log(dataBase = false, printBody = false)
	@ApiOperation("医生热度咨询列表订单查询")
	@GetMapping(value = "/hot/labels/orders")
	public APIResponse<PageInfo<HotPointVo>> hotLabelsOrders(
			@RequestParam Long doctorId,
			@RequestParam(required = false) String labels,
			@RequestParam(defaultValue = "1") int pageNum,
			@RequestParam(defaultValue = "5") int pageSize
	) {
		PageHelper.startPage(pageNum, pageSize);
		List<HotPointVo> hotPointVos = commentRecordSV.hotLabelsOrders(doctorId, labels);
		return successData(new PageInfo<>(hotPointVos));
	}

	@Log
	@ApiOperation("医生擅长信息删除")
	@GetMapping(value = "/good/delete")
	public APIResponse delDoctorGood(Long labId) {
		Long doctId = ShiroUtil.getLoginId();
		boolean flag = resultDoctorService.delDoctorGood(labId, doctId);
		if (flag) {
			return successMsg("删除成功！");
		}
		return successMsg("删除失败！");
	}

	@Log
	@ApiOperation("医生擅长信息增加")
	@PostMapping(value = "/good/edit", consumes = MediaType.APPLICATION_JSON_VALUE)
	public APIResponse editDoctorGood(@RequestBody DoctorGoodParam doctorGood) {
		boolean flag = resultDoctorService.editDoctorGood(doctorGood.getLabels(), doctorGood.getDoctorId());
		if (flag) {
			return successMsg("医生擅长信息保存成功！");
		}
		return failMsg("医生擅长信息保存失败！");
	}

	@Log(dataBase = false, printBody = false)
	@ApiOperation("实名认证/资质认证查询")
	@GetMapping(value = "/authentication/select")
	public APIResponse<RelevantCertRecordEntity> selectAuthentication() {
		List<RelevantCertRecordEntity> relevantCertRecordList = relevantCertRecordSV.selectList(
				TK.select(RelevantCertRecordEntity.class).where()
				.andEqualTo(RelevantCertRecordEntity::getUserId,ShiroUtil.getLoginId())
				.end()
				.orderByClause("create_time desc")
		);
		return successData((relevantCertRecordList.isEmpty()) ? null : relevantCertRecordList.get(0));
	}

	@Log
	@ApiOperation("实名认证/资质认证")
	@PostMapping(value = "/authentication")
	public APIResponse<List<RelevantCertRecordEntity>> authentication(@RequestBody List<RelevantCertRecordEntity> relevantCertRecords) {
		resultDoctorService.authentication(relevantCertRecords, SessionContext.getCurrUser());
		return successData(relevantCertRecords);
	}


	@Log
	@ApiOperation("实名认证/资质认证修改")
	@PostMapping(value = "/authentication/update")
	public APIResponse updateAuthentication(@RequestBody List<RelevantCertRecordEntity> relevantCertRecords) {
		relevantCertRecordSV.updateBatchByIdSelective(relevantCertRecords);
		return success();
	}

	@Log
	@ApiOperation("医生端-账户余额")
	@GetMapping(value = "/account/balance")
	public APIResponse<AccountEntity> accountBalance() {
		Long userId = ShiroUtil.getLoginId();
		AccountEntity account = accountSV.selectAccount(userId);
		if (account == null) {
			return failMsg("不存在该账户！");
		}
		return successData(account);
	}

	@Log
	@ApiOperation("医生端-银行卡列表")
	@GetMapping(value = "/bankCard/list")
	public APIResponse<List<BankcardEntity>> listBankCard() {
		List<BankcardEntity> bankcards = resultDoctorService.listBankCard(ShiroUtil.getLoginId());
		return successData(bankcards);
	}

	@Log(dataBase = false, printBody = false)
	@ApiOperation("医生端-账户交易明细")
	@GetMapping(value = "/transaction/detail")
	public APIResponse<UserExpendIncomeVO> transactionDetail(@RequestParam(required = false) String tdTime,
															 @RequestParam(defaultValue = "1", required = false) int pageNum,
															 @RequestParam(defaultValue = "10", required = false) int pageSize) {
		Long userId = ShiroUtil.getLoginId();
		PageInfo<DoctorTdDetailsVO> doctorTdDetailsVOS = consumeDetailsSV.docTransactionDetail(userId, tdTime, pageNum, pageSize);
		UserExpendIncomeVO doctExpendIncomeVO = consumeDetailsSV.doctorExpendIncomeVO(userId, tdTime);    //收入支出情况
		doctExpendIncomeVO.setDoctorTdDetailsVOS(doctorTdDetailsVOS);
		return successData(doctExpendIncomeVO);
	}

	@Log(dataBase = false, printBody = false)
	@ApiOperation("医生端-账户收入支出")
	@GetMapping(value = "/doctor/expendIncome")
	public APIResponse<UserExpendIncomeVO> doctorExpendIncomeVO(@RequestParam(required = false) String tdTime) {
		UserExpendIncomeVO doctExpendIncomeVO = consumeDetailsSV.doctorExpendIncomeVO(ShiroUtil.getLoginId(), tdTime);
		return successData(doctExpendIncomeVO);
	}

	@Log
	@ApiOperation("收藏-医生列表")
	@GetMapping(value = "/collect/doctor")
	public APIResponse<PageInfo<ResultDoctor>> collectDoctor(@RequestParam(defaultValue = "1", required = false) int pageNum,
															 @RequestParam(defaultValue = "5", required = false) int pageSize) {
		PageInfo<ResultDoctor> list = resultDoctorService.collectDoctorList(pageNum, pageSize, ShiroUtil.getLoginId());
		return successData(list);
	}

	@Log(dataBase = false, printBody = false)
	@ApiOperation(value = "医生-患者评价标签")
	@GetMapping(value = "/patientRateTag")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "doctorId", value = "医生ID", required = false, paramType = "query"),
	})
	@ResponseBody
	public APIResponse<List<PatientRateTagVo>> patientRateTag(
			Long doctorId
	) {
		if (doctorId == null) {
			doctorId = ShiroUtil.getLoginId();
		}

		String sql = "select * from(   SELECT " +
				"b.id, " +
				"a.tag_type, " +
				"count(0) num, " +
				"b.tglb_name tglbName " +
				"from user_taglibrary a " +
				"inner join standar_taglibrary b on a.tag_id = b.id and a.tag_type = '01' " +
				"where taged_user_id = #{params.doctorId} and b.tglb_type = '01' " +
				"UNION ALL " +
				"SELECT " +
				"b.id, " +
				"a.tag_type, " +
				"count(0) num, " +
				"b.tglb_name tglbName " +
				"from user_taglibrary a " +
				"inner join custom_taglibrary b on a.tag_id = b.id and a.tag_type = '02' " +
				"where taged_user_id = #{params.doctorId} and b.tglb_type = '01'" +
				") tab where id is not null ";
		Map<String, Object> params = new HashMap<>();
		params.put("doctorId", doctorId);
		List<PatientRateTagVo> list = commonSV.queryListEntity(sql, params, PatientRateTagVo.class);
		return successData(list);
	}

	@Log(dataBase = false, printBody = false)
	@ApiOperation(value = "医生-患者满意度")
	@GetMapping(value = "/patientSatisfaction")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "doctorId", value = "医生ID", required = false, paramType = "query"),
	})
	@ResponseBody
	public APIResponse<Map<String, Object>> patientSatisfaction(
			Long doctorId
	) {
		if (doctorId == null) {
			doctorId = ShiroUtil.getLoginId();
		}
		String sql = " SELECT " +
				" count(tglb_level) countSum, " +
				"  tglb_level levels " +
				"FROM " +
				" ( " +
				"  SELECT " +
				"      DISTINCT a.order_id, " +
				"   b.tglb_level " +
				"  FROM " +
				"   user_taglibrary a " +
				"  INNER JOIN standar_taglibrary b ON a.tag_id = b.id " +
				"  AND a.tag_type = '01' " +
				"  WHERE " +
				"   taged_user_id = #{params.doctorId} and b.tglb_type = '01'   " +
				"  UNION  " +
				"   SELECT " +
				"     DISTINCT a.order_id, " +
				"    b.tglb_level " +
				"   FROM " +
				"    user_taglibrary a " +
				"   INNER JOIN custom_taglibrary b ON a.tag_id = b.id " +
				"   AND a.tag_type = '02' " +
				"   WHERE " +
				"    taged_user_id = #{params.doctorId} and b.tglb_type = '01'  " +
				" ) tab group by tglb_level";
		Map<String, Object> params = new HashMap<>();
		params.put("doctorId", doctorId);
		List<JSONObject> list = commonSV.queryListJson(sql, params);
		JSONObject result = new JSONObject();
		result.put("满意", 0);
		result.put("一般", 0);
		result.put("不满意", 0);
		int sumOrder = 0;
		for (JSONObject jsonObject : list) {
			String levels = jsonObject.getString("levels");
			Integer countSum = jsonObject.getInteger("countSum");
			sumOrder += countSum;
			if (StringUtils.isNotBlank(levels)) {
				if (levels.matches("04|05")) {
					result.put("满意", result.getIntValue("满意") + countSum);
				} else if (levels.matches("03|02")) {
					result.put("一般", result.getIntValue("一般") + countSum);
				} else if (levels.matches("01")) {
					result.put("不满意", result.getIntValue("不满意") + countSum);
				}
			}
		}
		result.put("全部", sumOrder);
		return successData(result);
	}

	@Log(dataBase = false, printBody = false)
	@ApiOperation(value = "医生-患者评价")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "doctorId", value = "医生ID", required = false, paramType = "query"),
			@ApiImplicitParam(name = "okay", value = "满意度，1满意2一般3不满意", required = false, paramType = "query"),
			@ApiImplicitParam(name = "tagStand", value = "标准标签ID，多个", required = false, paramType = "query"),
			@ApiImplicitParam(name = "tagCustom", value = "自定义标签ID，多个", required = false, paramType = "query"),
	})
	@GetMapping(value = "/patientRate")
	@ResponseBody
	public APIResponse<PageInfo<HotPointVo>> patientRate(
			Long doctorId,
			@RequestParam(required = false) String okay,
			@RequestParam(required = false) Long[] tagStand,
			@RequestParam(required = false) Long[] tagCustom,
			@RequestParam(defaultValue = "1") int pageNum,
			@RequestParam(defaultValue = "5") int pageSize
	) {
		if (doctorId == null) {
			doctorId = ShiroUtil.getLoginId();
		}
		PageHelper.startPage(pageNum, pageSize);
		List<HotPointVo> commentRecordVos = commentRecordSV.selectCommentRecords(okay, doctorId, tagStand, tagCustom);
		return successData(new PageInfo<>(commentRecordVos));
	}

	@Log(dataBase = false, printBody = false)
	@ApiOperation(value = "今日订单/患者评价/推荐指数")
	@GetMapping(value = "/statistical/self")
	public APIResponse<DoctorSelfIndexCountVO> statisticalSelfData(
			Long doctId
	) {
		if (doctId == null) {
			doctId = ShiroUtil.getLoginId();
		}
		DoctorSelfIndexCountVO data = doctorSelfSV.statisticalSelfData(doctId);
		return successData(data);
	}

	@Log(dataBase = false, printBody = false)
	@ApiOperation("查询患者的问诊记录")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "patientId", value = "患者ID", required = false, paramType = "query", dataType = "Long"),
			@ApiImplicitParam(name = "type", value = "查询类型 （01-当前接诊 02 历史接诊）", required = true, paramType = "query", dataType = "String")
	})
	@ApiResponses({
			@ApiResponse(code = 200, message = "请求成功", response = CounsellingRoomRecordVO.class),
	})
	@GetMapping(value = "/inquiry/record/list")
	public APIResponse<PageInfo<CounsellingRoomRecordVO>> recordList(Long patientId, @RequestParam String type,
																	 @RequestParam(defaultValue = "1") int pageNum,
																	 @RequestParam(defaultValue = "5") int pageSize) {
		CounsellingRoomParam model = new CounsellingRoomParam();
		model.setPatientId(patientId);
		model.setUserId(ShiroUtil.getLoginId());
		PageInfo<CounsellingRoomRecordVO> counsellingRoomPageInfo = null;
		if ("01".equals(type)) {
			/*咨询室状态 未答复 已答复*/
			model.setCourStates(CounsellingRoomStateEnum.DID_NOT_RETURN.getKey() + "," + CounsellingRoomStateEnum.HAVE_A_REPLY.getKey());
			/*订单状态 已接单*/
			model.setIoStates(InquiryOrderStateEnum.HAVE_ORDER.getKey());
			counsellingRoomPageInfo = counsellingRoomService.listPagePatientVisitRecord(model, pageNum, pageSize);
		} else {
			model.setCourStates(CounsellingRoomStateEnum.HAS_ENDED.getKey() + "," + CounsellingRoomStateEnum.NOT_TO_SUMMARIZE.getKey() + "," + CounsellingRoomStateEnum.HAVE_SUMMARIZED.getKey());
			model.setIoStates(InquiryOrderStateEnum.COMPLETE.getKey() + "," + InquiryOrderStateEnum.CANCEL.getKey());
			counsellingRoomPageInfo = counsellingRoomService.listPagePatientVisitRecord(model, pageNum, pageSize);
		}
		return successData(counsellingRoomPageInfo);
	}

	@Log(dataBase = false, printBody = false)
	@ApiOperation("查询医生开通的服务项")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "doctorId", value = "医生ID", required = false, paramType = "query", dataType = "Long"),
	})
	@GetMapping(value = "/openService/list")
	public APIResponse<List<OpenServiceListVo>> openServiceList(
			Long doctorId
	) {
		if (doctorId == null) {
			doctorId = ShiroUtil.getLoginId();
		}

		List<OpenServiceListVo> srviceItem = doctorServiceItemSV.openServiceList(doctorId);
		return successData(srviceItem);
	}

	@Log(dataBase = false, printBody = false)
	@ApiOperation("医生-今日/历史 订单统计")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "orderDate", value = "订单日期类型，01今日02累计，默认全部", required = false, paramType = "query"),
	})
	@GetMapping(value = "/orderStats")
	public APIResponse<Map<String, Object>> orderStats(
			@RequestParam(required = false) @Pattern(regexp = "01|02") String orderDate
	) {
		Map<String, Object> result = new HashMap<>();
		Map<String, Object> params = new HashMap<>();
		params.put("doctorId", ShiroUtil.getLoginId());
		if (StringUtils.isBlank(orderDate) || "02".equals(orderDate)) {
			Long orderDay = 0L;
			Long orderHisDay = 0L;
			String sqlDay = " select count(1) orderNum,io_type ioType " +
					" from order_flow_record_view ha " +
					" INNER JOIN inquiry_order hc on hc.id = ha.order_id " +
					" left join doctor_studio hb on hb.id = ha.doctor_ds_id " +
					" where ha.STATUS > '03' and  doctor_id = #{params.doctorId}" +
					" group by ioType";
			// 历史订单
			List<DoctorOrderStatsVo> historyOrder = commonSV.queryListEntity(sqlDay, params, DoctorOrderStatsVo.class);
			historyOrder = resetOrders(historyOrder);
			result.put("historyOrder", historyOrder);
			result.put("historyOrderNum", historyOrder.stream().mapToInt(DoctorOrderStatsVo::getOrderNum).sum());
		}
		if (StringUtils.isBlank(orderDate) || "01".equals(orderDate)) {
			// 今日订单
			String sqlDay = " select count(1) orderNum,io_type ioType " +
					" from order_flow_record_view ha " +
					" INNER JOIN inquiry_order hc on hc.id = ha.order_id " +
					" left join doctor_studio hb on hb.id = ha.doctor_ds_id " +
					" where ha.STATUS > '03' and   doctor_id = #{params.doctorId} " +
					"  AND ( " +
					"   doctor_order_time BETWEEN DATE_FORMAT( " +
					"    CURDATE(), " +
					"    '%Y-%m-%d %H:%i:%s' " +
					"   ) " +
					"   AND now() " +
					"  ) " +
					" group by ioType";
			List<DoctorOrderStatsVo> todayOrder = commonSV.queryListEntity(sqlDay, params, DoctorOrderStatsVo.class);
			todayOrder = resetOrders(todayOrder);
			result.put("todayOrder", todayOrder);
			result.put("todayOrderNum", todayOrder.stream().mapToInt(DoctorOrderStatsVo::getOrderNum).sum());
		}
		return successData(result);
	}

	@Log(dataBase = false, printBody = false)
	@ApiOperation("医生-订单统计(含工作室)")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "orderDate", value = "订单日期，格式yyyy-MM", required = true, paramType = "query"),
			@ApiImplicitParam(name = "orderType", value = "订单统计类型： 专科：01友医工作室订单02个人工作室订单03个人订单，默认全部；全科：01助理接单02自己接单，默认全部", required = false, paramType = "query"),
			@ApiImplicitParam(name = "doctorId", value = "医生ID,默认自己", required = false, paramType = "query"),
	})
	@GetMapping(value = "/orderReport")
	public APIResponse<Map> orderReport(
			@RequestParam @Pattern(regexp = "^\\d{4}-\\d{2}$") String orderDate,
			@Pattern(regexp = "01|02|03") String orderType,
			Long doctorId,
			@RequestParam(defaultValue = "5") int pageSize,
			@RequestParam(defaultValue = "1") int pageNum
	) {
		if (doctorId == null) {
			doctorId = ShiroUtil.getLoginId();
		}
		PageHelper.startPage(pageNum, pageSize);
		CounsellingRoomCourTypeEnum doctorType = SessionContext.getCurrDoctorType();
		List<OrdersVo> list = inquiryOrderSV.orderReport(orderDate, doctorType.getKey(), orderType, doctorId);
		PageInfo<OrdersVo> ordersVoPageInfo = new PageInfo<>(list);
		Long countSum = ordersVoPageInfo.getTotal();
		Double countAmount = inquiryOrderSV.orderReportCountAmount(orderDate, doctorType.getKey(), orderType, doctorId);
		Map<String, Object> result = new HashMap<>();
		result.put("countSum", countSum);
		result.put("countAmount", countAmount);
		result.put("pageData", ordersVoPageInfo);
		return successData(result);
	}

	@Log(dataBase = false, printBody = false)
	@ApiOperation("医生-订单统计详情")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "orderId", value = "订单ID", required = true, paramType = "query"),
	})
	@GetMapping(value = "/orderReport/info")
	public APIResponse<MyOrderInfoVo> orderReportInfo(
			@RequestParam Long orderId
	) {
		MyOrderInfoVo myOrderInfoVo = inquiryOrderSV.orderReportInfo(orderId,SessionContext.getCurrDoctorStudio());
		return successData(myOrderInfoVo);
	}

	/**
	 * 补足数据
	 *
	 * @param orders
	 */
	private List<DoctorOrderStatsVo> resetOrders(List<DoctorOrderStatsVo> orders) {
		List<DoctorOrderStatsVo> result = new ArrayList<>();
		//补足数据
		Map<String, String> dictValues = sysDictSV.getDictValuesToMap(InquiryOrderIoTypeEnum.class);
		List<String> exisitIoType = new ArrayList<>();
		for (DoctorOrderStatsVo doctorOrderStatsVo : orders) {
			result.add(doctorOrderStatsVo);
			exisitIoType.add(doctorOrderStatsVo.getIoType());
		}
		dictValues.forEach((key, value) -> {
			if (!exisitIoType.contains(key)) {
				DoctorOrderStatsVo vo = new DoctorOrderStatsVo();
				vo.setIoType(key);
				vo.setOrderNum(0);
				result.add(vo);
			}
		});
		return result;
	}


	@Log(dataBase = false, printBody = false)
	@ApiOperation("医生-今日/历史 订单详情")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "parentType", value = "01今日/02累计", required = true, paramType = "query"),
			@ApiImplicitParam(name = "ioType", value = "订单类型,不传默认全部", required = false, paramType = "query"),
	})
	@GetMapping(value = "/orderStats/info")
	public APIResponse<PageInfo<OrdersVo>> orderStatsInfo(
			@Pattern(regexp = "01|02", message = "请输入正确的类型！") String parentType,
			@CustomConstraint(InquiryOrderIoTypeEnum.class) String ioType,
			@RequestParam(defaultValue = "1") int pageNum,
			@RequestParam(defaultValue = "5") int pageSize
	) {
		Map<String, Object> params = new HashMap<>();
		params.put("doctorId",ShiroUtil.getLoginId());
		String sqlDay = "select   " +
				"hc.id,  " +
				"hc.user_id userId,  " +
				"hc.patient_id patientId,  " +
				"he.name name,  " +
				"hd.head_url head,  " +
				"TIMESTAMPDIFF(YEAR,he.birthday,date_format(now(), '%Y-%m-%d')) age,  " +
				"he.sex sex,  " +
				"ha.doctor_order_time time,  " +
				"hc.illness_desc content,  " +
				"hc.payable_amount amount,  " +
				"hc.order_source orderSource,  " +
				"hc.io_type ioType,  " +
				"hb.ds_name dsName " +
				"from order_flow_record_view ha    " +
				"INNER JOIN inquiry_order hc on hc.id = ha.order_id    " +
				"LEFT JOIN doctor_studio hb on hb.id = ha.doctor_ds_id    " +
				"LEFT JOIN user_patient_view hd on hd.id = hc.user_id  " +
				"LEFT JOIN patient_detail he on he.id = hc.patient_id  " +
				" where  ha.STATUS > '03' and doctor_id = #{params.doctorId} ";
		if (StringUtils.isNotBlank(ioType)) {
			sqlDay += " and hc.io_type = #{params.ioType}";
			params.put("ioType", ioType);
		}
		if ("01".equals(parentType)) {
			// 今日订单
			sqlDay += "  AND ( " +
					"   doctor_order_time BETWEEN DATE_FORMAT( " +
					"    CURDATE(), " +
					"    '%Y-%m-%d %H:%i:%s' " +
					"   ) " +
					"   AND now() " +
					"  ) ";
		}
		sqlDay += " order by ha.doctor_order_time desc";
		PageInfo<OrdersVo> todayOrder = commonSV.queryPage(sqlDay, params, pageNum, pageSize, OrdersVo.class);
		return successData(todayOrder);
	}

	@Log
	@ApiOperation("消息列表展示")
	@GetMapping(value = "/information/list")
	public APIResponse<PageInfo<InformationEntity>> informationList(
			InformationParam model,
			@RequestParam(defaultValue = "1", required = false) int pageNum,
			@RequestParam(defaultValue = "5", required = false) int pageSize
	) {
		model.setReceiverObjId(ShiroUtil.getLoginId());
		PageDomain.startPage(pageNum,pageSize,"create_time","desc");
		List<InformationEntity> info = informationSV.selectList(model.covert());
		return successPage(info);
	}

	@Log
	@ApiOperation("消息未读数量")
	@GetMapping(value = "/information/unread")
	public APIResponse<List<InformationVo>> informationUnread() {
		List<InformationVo> unread = informationSV.informationUnread(ShiroUtil.getLoginId());
		return successData(unread);
	}

	@Log
	@ApiOperation("消息清空删除")
	@PostMapping(value = "/information/clean", consumes = MediaType.APPLICATION_JSON_VALUE)
	public APIResponse informationClean(
			@NotNull Long[] ids
	) {
		for (Long id : ids) {
			informationSV.deleteById(id);
		}
		return success();
	}

	@ApiOperation("设置消息未已读")
	@PostMapping(value = "/information/setRead", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
	public APIResponse informationSetRead(
			@NotNull Long id
	) {
		InformationEntity unread = new InformationEntity();
		unread.setId(id);
		unread.setInforState(InformationInforStateEnum.OVER_READ.getKey());
		informationSV.updateById(unread);
		return success();
	}

	/*@ApiOperation("医生提现到银行卡")
	@PostMapping(value = "/account/embody")
	public APIResponse<PersonalTransactionOrder> accountEmbody(@RequestBody PersonalTransactionOrder personalTransactionOrder) {
		//获取用户账户主键
		Account doctorAcc = accountSV.selectAccountByUserId(ShiroUtil.getLoginId());

		personalTransactionOrderSV.accountEmbody(personalTransactionOrder, doctorAcc);
		return successMsg("医生提现成功");
	}*/

	@Log(dataBase = false, printBody = false)
	@ApiOperation("模板列表查询")
	@GetMapping(value = "/template/list")
	public APIResponse<PageInfo<UserReplayTemplateEntity>> templateList(
			UserReplayTemplateParam userReplayTemplateModel,
			@RequestParam(defaultValue = "1", required = false) int pageNum,
			@RequestParam(defaultValue = "5", required = false) int pageSize
	) {
		// 默认当前用户模板查询
		Long creSb = userReplayTemplateModel.getCreSb();
		if (creSb == null) {
			userReplayTemplateModel.setTheDel(FlagEnum.NO.getKey());
			userReplayTemplateModel.setCreSb(ShiroUtil.getLoginId());
		}
		PageDomain.startPage(pageNum,pageSize);
		List<UserReplayTemplateEntity> userReplayTemplatePageInfo = userReplayTemplateSV.selectList(userReplayTemplateModel.covert());
		return successPage(userReplayTemplatePageInfo);
	}

	@Log
	@ApiOperation("模板新增修改")
	@PostMapping(value = "/template/update", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public APIResponse templateUpdate(
			@RequestBody UserReplayTemplateEntity userReplayTemplate
	) {
		if (userReplayTemplate.getId() == null || userReplayTemplate.getId() < 0) {
			//表示新增
			userReplayTemplate.setCreSb(ShiroUtil.getLoginId());
			userReplayTemplateSV.insert(userReplayTemplate);
		} else {
			//表示修改
			userReplayTemplateSV.updateById(userReplayTemplate);
		}

		return success();
	}

	@ApiOperation("医生信息完善进度展示")
	@GetMapping(value = "/doctorUpdateInfo/list")
	public APIResponse<List<DoctorUpdateInfoVo>> listDoctorUpdateInfo() {
		return successData(doctorUpdateInfoSV.listDoctorUpdateInfo(ShiroUtil.getLoginId()));
	}

	@ApiOperation("医生信息完善")
	@PostMapping(value = "/doctorUpdateInfo/fill")
	public APIResponse<Long> fillDoctorUpdateInfo(@ApiParam(name = "doctorUpdateRelation", value = "医生关联信息实体", required = true)
												  @RequestBody DoctorUpdateRelationEntity doctorUpdateRelation) {
		doctorUpdateRelation.setDoctId(ShiroUtil.getLoginId());
		doctorUpdateRelationSV.insert(doctorUpdateRelation);
		return failMsg("医生完善信息新增失败!");
	}

	@ApiOperation("医院列表展示")
	@GetMapping(value = "/listHospital")
	public APIResponse<PageInfo<HospitalEntity>> listHospital(HospitalParam model,
															  @RequestParam(defaultValue = "1", required = false) int pageNum,
															  @RequestParam(defaultValue = "5", required = false) int pageSize) {
		return successData(hospitalSV.getHospitalList(pageNum, pageSize, model));
	}

	@ApiOperation("擅长标签展示")
	@GetMapping(value = "/listLabels")
	public APIResponse<List<LabelsVo>> listLabels(LabelsParam model) {
		return successData(labelsSV.listLabels(model));
	}

	@ApiOperation("医生添加擅长信息")
	@PostMapping(value = "/addLabels")
	public APIResponse addLabels(@RequestBody List<Long> labelIds) {
		if (labelIds == null || labelIds.isEmpty()) {
			return failMsg("请至少选择一个");
		}
		Long doctorId = ShiroUtil.getLoginId();
		for (Long labelId : labelIds) {
			DoctorLabelEntity doctorLabel = new DoctorLabelEntity();
			doctorLabel.setLabId(labelId);
			doctorLabel.setDoctId(doctorId);
			doctorLabelSV.insert(doctorLabel);
		}
		return successMsg("医生添加擅长信息成功");
	}

	@ApiOperation("医生删除擅长信息")
	@PostMapping(value = "/delDocLabels")
	public APIResponse delDocLabels(@RequestBody Long[] doctorLabelId) {
		if (doctorLabelId.length <= 0) {
			return failMsg("请至少选择一个");
		}
		doctorLabelSV.deleteByIds(doctorLabelId);
		return successMsg("医生删除擅长信息成功");
	}

	@ApiOperation("医生保存擅长信息")
	@PostMapping(value = "/saveLabels")
	public APIResponse saveLabels(@RequestBody List<DoctorLabelEntity> doctorLabels) {
		if (doctorLabels == null || doctorLabels.isEmpty()) {
			return failMsg("请至少选择一个");
		}
		//清除该医生之前所有的标签
		doctorLabelSV.deleteByParams(DoctorLabelEntity.builder().doctId(ShiroUtil.getLoginId()).build());
		doctorLabelSV.batchInsert(doctorLabels);
		return successMsg("医生添加擅长信息成功");
	}
}
